package com.etymgiko.lyricshere.web.admin.artist;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;

import javax.servlet.http.HttpServletRequest;

import com.etymgiko.lyricshere.manager.ArtistManager;
import com.etymgiko.lyricshere.model.Artist;

/**
 *
 * @author Ivan Holub
 */
public class EditArtistFormController extends SimpleFormController {

    private ArtistManager artistManager;

    public void setArtistManager(ArtistManager artistManager) {
        this.artistManager = artistManager;
    }

    protected ModelAndView onSubmit(Object o) throws Exception {

        ArtistCommand command = (ArtistCommand) o;

        Artist artist = new Artist();
        artist.setId(Long.valueOf(command.getId()));
        artist.setName(command.getName());
        artist.setCode(command.getCode());
        artistManager.updateArtist(artist);

        ModelAndView mav = new ModelAndView(getSuccessView() + "?id=" + artist.getId());
        return mav;
    }

    @Override
    protected Object formBackingObject(HttpServletRequest httpServletRequest) throws Exception {
        String id = httpServletRequest.getParameter("id");
        Artist artist = artistManager.getArtist(Long.valueOf(id));
        ArtistCommand command = new ArtistCommand();
        command.setId(artist.getId().toString());
        command.setName(artist.getName());
        command.setCode(artist.getCode());
        return command;
    }

    @Override
    protected void initBinder(HttpServletRequest httpServletRequest, ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
    }
}